package com.zoffy.ybuhelper;

import android.annotation.SuppressLint;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.*;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.zoffy.ybuhelper.util.HttpUtil;
import org.apache.http.Header;
import org.apache.http.HttpResponse;

public class StudyWebActivity extends AppCompatActivity {
    private CookieManager cookieManager=CookieManager.getInstance();
    private int statusCode;
    private SharedPreferences preferences;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web);
        init();
        preferences = getSharedPreferences("user_data",MODE_PRIVATE);
        String account= preferences.getString("account",null);
        String password= preferences.getString("password",null);
        getCookie(account,password);


    }

    //进行初始设置
    @SuppressLint("SetJavaScriptEnabled")
    protected void init(){
        cookieManager.setAcceptCookie(true);
        cookieManager.removeAllCookies(null);
        cookieManager.flush();

        //设置webview属性
        WebView webView=findViewById(R.id.webview);
        webView.setInitialScale(25);
        webView.clearCache(true);
        webView.clearFormData();
        webView.clearHistory();
        webView.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if(event.getAction()==KeyEvent.ACTION_DOWN && keyCode==KeyEvent.KEYCODE_BACK &&webView.canGoBack()){
                    webView.goBack();
                    return true;
                }
                return false;
            }
        });

        webView.setWebViewClient(new WebViewClient(){
            @Nullable
            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
                if(!request.isForMainFrame() && request.getUrl().getPath().endsWith("/favicon.ico")){
                    return new WebResourceResponse("image/png",null,null);
                }
                return super.shouldInterceptRequest(view, request);
            }
            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                if(!request.getUrl().getPath().endsWith("/favicon.ico"))
                    Toast.makeText(StudyWebActivity.this,"网络异常",Toast.LENGTH_SHORT).show();
            }
        });
        WebSettings settings = webView.getSettings();
        settings.setUseWideViewPort(true);
        settings.setBuiltInZoomControls(true);
        settings.setDisplayZoomControls(false);
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        settings.setJavaScriptEnabled(true);
        findViewById(R.id.refresh).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                WebView webView=findViewById(R.id.webview);
                webView.loadUrl("http://jwxt.ybu.edu.cn/jsxsd/framework/xsMain.jsp");
            }
        });




    }
    //对教务系统登录api进行登录请求并跳转教务系统个人主页
    protected void getCookie(String account,String password) {

        //通过HttpClient获取登录凭证
        Thread cookieThread =new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    HttpResponse response = HttpUtil.login(account,password);
                    Header[] headers = response.getHeaders("Set-Cookie");
                    statusCode=response.getStatusLine().getStatusCode();
                    for(Header header:headers)
                        cookieManager.setCookie("jwxt.ybu.edu.cn",header.getValue());
                    cookieManager.flush();
                } catch (Exception e) {
                    Log.d("日志",e.toString());
                }
            }
        });
        cookieThread.start();
        try {
            cookieThread.join();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }



        //通过状态码判断是否登陆成功，登录成功的状态码为304，失败为200
        if (statusCode==200){
            Toast.makeText(StudyWebActivity.this,"登陆失败，检查密码是否正确",Toast.LENGTH_SHORT).show();
        }
        else{
            WebView webView=findViewById(R.id.webview);
            webView.loadUrl("http://jwxt.ybu.edu.cn/jsxsd/framework/xsMain.jsp");
        }

    }
}
